<template>
  <div
    class="page-content"
    :element-loading-text="loadText"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    v-loading="!load"
  >
    <Menu :menuData="menuData" v-if="menuData.length" />
    <el-tooltip
      effect="dark"
      content="退出登录"
      placement="left"
      v-if="load && isRoot"
    >
      <SvgIcon
        class="logout"
        icon="exit"
        v-show="store.showUi"
        @click="logout"
      />
    </el-tooltip>
    <div class="CIM-container" id="CIM-container"></div>
    <optimize v-if="load"></optimize>
    <event-menu v-if="load" :isRoot="isRoot"></event-menu>
    <iframe
      v-if="load && panoShow"
      frameborder="0"
      noresize="noresize"
      style="
        position: fixed;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 1000;
      "
      :src="panoUrl"
    />
    <el-tooltip
      effect="dark"
      content="返回"
      placement="bottom"
      v-if="load && panoShow"
    >
      <SvgIcon
        style="
          position: fixed;
          top: 20px;
          left: 20px;
          fontsize: 25px;
          color: #fff;
          z-index: 1000;
          cursor: pointer;
        "
        icon="goback"
        @click="panoShow = false"
      />
    </el-tooltip>
    <router-view
      class="router-container"
      v-if="load"
      v-show="store.showUi && store.showWindow"
    ></router-view>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import { initViewer } from "../plugin/map";
import Menu from "./components/Menu/Menu.vue";
import _request, { mergeRequest } from "../utils/request";
import { useLayerStore } from "../store/layer";
import { useVideoStore } from "../store/video";
import { useStore } from "../store/store";
import { getUserInfoById, getSenceById } from "../api/login";
import { getSenceMenuList, getSenceFunction } from "../api/system";
import { useRouter, useRoute } from "vue-router";
import { menuMap } from "../router/router";
import SvgIcon from "../components/SvgIcon.vue";
import eventMenu from "./eventMenu/index.vue";
import panoPopup from "./panoPopup/index.vue";
import optimize from "./optimize.vue";

import { resetVariable, globalTool } from "../../static/CIM/BQGIS-globalVar";

const layerStore = useLayerStore();
const videoStore = useVideoStore();
const store = useStore();
const load = ref(false); // 检查用户信息完成
const router = useRouter();
const route = useRoute();
const menuData = ref([]);
let defaultMenu = null; // 场景的默认功能
const loadText = ref("正在验证账号信息...");
const isRoot = ref(false); // 是否为管理员账号
const panoShow = ref(false);
const panoUrl = ref("");

onMounted(() => {
  initViewer();
  store.initFrame();
  getUserInfoById({ id: window.sessionStorage.getItem("userId") })
    .then((res) => {
      store.loginInfo = res;
      window.sessionStorage.setItem("username", res.username);
      isRoot.value = res.isroot === 0;
      if (isRoot.value) {
        adminUser();
      } else {
        normalUser();
      }
      onClickPano();
    })
    .finally(() => {});
});

onUnmounted(() => {
  store.destroyFrame();
  window.viewer.destroy();
  window.viewer = null;
  resetVariable();
  videoStore.clear();
});

function onClickPano() {
  // 右键3dtiles，点击编辑菜单
  if (!globalTool.eventTarget) {
    globalTool.eventTarget = new mars3d.BaseClass(); // viewer 自定义事件实例
  }
  globalTool.eventTarget.on("clickPano", function (e) {
    if (e.graphic.attr.url) {
      panoShow.value = true;
      panoUrl.value = e.graphic.attr.url;
    }
  });
}

function logout() {
  window.sessionStorage.clear();
  router.push("/login");
}

function adminUser() {
  // 管理员账号
  load.value = true;
  getSenceFunction().then((treeData) => {
    let arr = setTreeData(treeData);
    menuData.value = arr;
  });
  layerStore.getTreeData().then(() => {
    layerStore.loadTreeData();
  });
}

function normalUser() {
  let doNotLoad = false; // 页面加载后是否需要加载模型
  // 普通账号，开始检查sceneID
  const sceneId = window.sessionStorage.getItem("sceneId");
  if (!sceneId) {
    return router.push("/login");
  }

  getSenceById({ id: sceneId }).then((res) => {
    if (res.coord) {
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(...res.coord.split(",")),
      });
    }
  });
  getSenceFunction({ senceId: sceneId })
    .then((treeData) => {
      loadText.value = "加载功能...";
      menuData.value = setTreeData(filterTreeData(treeData));
      if (defaultMenu) {
        doNotLoad =
          defaultMenu.name === "多屏对比" &&
          (route.path === "/" || route.name === "mutilScreenComparision"); // 当默认功能是多屏对比时，加载页面时不预加载模型
        if (route.path === "/") {
          router.push({ name: defaultMenu.routerName });
        }
      }
      return doNotLoad
        ? layerStore.getSceneTreeDataDoNotLoad(viewer, sceneId)
        : layerStore.getSceneTreeData(viewer, sceneId);
    })
    .then(() => {
      load.value = true;
      if (!doNotLoad) {
        layerStore.loadTreeData();
      }
    })
    .catch((err) => {
      console.error(err);
      router.push("/login");
    });
}

function filterTreeData(data) {
  const filterData = [];
  data.forEach((item) => {
    if (item.children && item.children.length) {
      const temp = item.children.filter((item) => item.checked);
      if (temp.length) {
        item.children = temp;
        filterData.push(item);
      }
    }
  });
  return filterData;
}
function setTreeData(data) {
  return data.map((item) => {
    const d = menuMap[item.name];
    const obj = d ? { ...item, ...d } : item;
    if (item.children) {
      obj.children = setTreeData(item.children);
      return obj;
    } else {
      if (obj.isdefault === 1) {
        defaultMenu = obj;
      }
      return obj;
    }
  });
}
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;
  .CIM-container {
    width: 100%;
    height: 100%;
  }
  .logout {
    position: absolute;
    z-index: 9;
    right: 10px;
    top: 10px;
    color: rgba(255, 255, 255, 0.5);
    cursor: pointer;
  }
  .logout:hover {
    color: #fff;
  }
  .router-container {
    position: absolute;
    // background-color: rgba($color: #51594f, $alpha: 0.8);
    color: #fff;
    z-index: 9;
  }
}
</style>